package com.david.func_test.widget

import android.animation.ValueAnimator
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import com.david.func_test.R
import kotlin.math.sqrt

/**
 * bubbleWidth: 气泡控件宽度
 * centerWidth：围绕的中心点横坐标
 * centerHeight：围绕的中心点纵坐标
 */
class BubbleItemsWidget(var parent: FrameLayout, var bubbleWidth: Int, var centerWidth: Int, var centerHeight: Int, var radiusDistance: Int) {
    private var valueAnimator = ValueAnimator.ofInt(0, 30)
    private var items: ArrayList<AnimItemBean> = ArrayList()
    private var itemViews: ArrayList<View> = ArrayList()
    fun setItems(temps: ArrayList<AnimItemBean>?){
        items.clear()
        if (temps != null) {
            items.addAll(temps)
        }
        for (item in itemViews) {
            parent.removeView(item)//移除气泡
        }
        itemViews.clear()
        if (items.size > 0) {// TODO: 根据半径及横向距离计算marginTop

            for ((index, item) in items.withIndex()) {
                val view = ImageView(parent.context)
                view.setImageResource(R.mipmap.ic_launcher)
                val params = FrameLayout.LayoutParams(bubbleWidth, bubbleWidth)
                params.leftMargin = centerWidth - radiusDistance + 100 + (index) * (bubbleWidth + 20)
                params.topMargin = centerHeight - sqrt((radiusDistance * radiusDistance - (centerWidth - params.leftMargin) * (centerWidth - params.leftMargin)).toDouble())
                    .toInt()
                view.layoutParams = params
                parent.addView(view)
                itemViews.add(view)

                items[index].topMargin = params.topMargin
            }
            startAnim()
        }
    }

    private fun startAnim(){
        if (valueAnimator.isRunning) {
            return
        }
        valueAnimator.duration = 1000
        valueAnimator.repeatCount = ValueAnimator.INFINITE
        valueAnimator.repeatMode = ValueAnimator.REVERSE
        valueAnimator.addUpdateListener { animator -> // 获得每次变化后的属性值
            val currentValue = animator.animatedValue as Int

//            view.updateLayoutParams<ViewGroup.MarginLayoutParams> {
//                topMargin = 50 + currentValue
//            }
            for ((index, view) in itemViews.withIndex()) {
                (view.layoutParams as FrameLayout.LayoutParams).topMargin = items[index].topMargin + currentValue
            }
            parent.requestLayout()
        }
        valueAnimator.start()
    }

    fun stopAnim(){
        if (valueAnimator.isRunning) {
            valueAnimator.cancel()
        }
    }

    fun onDestroy(){
        stopAnim()
    }
}

